
const {User} = require('../model/dbModel/User')
const {SALT} =  require('../config/systemconfig')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')

/**
 * 
 * @api {post} /user/register 用户注册
 * @apiName apiName
 * @apiGroup user
 * @apiVersion  1.0.0
 * @apiDescription 注册一个用户
 * 
 * 
 */
async function register(user){
    const { username,password,usernickname,userrole} = user
    console.log(username,password)
    const model = await User.findOne({
        where:{
            username
        }
    })
    //判断用户是否存在
    if(model){
        return "用户已存在";
    }

    //用户不存在，开始创建用户
    //加密
    const cryptpwd = bcrypt.hashSync(password,SALT);
    const createUser = await  User.create({
        username:username,
        password:cryptpwd,
        usernickname:usernickname,
        userrole:userrole
    })
    return "用户创建成功";
}

/**
 * 
 * @api {get} /user/login title23
 * @apiName 登录成功生成token返回给客户端
 * @apiVersion 1.0.0
 * @apiGroup user
 */
async function login(user){
    const { username,password } = user

    if(username===undefined||password===undefined){
        return "账户名或密码错误";
    }
    const model = await User.findOne({
        where:{
            username
        }
    })
    // 判断数据库是否存在该用户
    if(!model){
        return "该用户不存在";
    }
    // 判断账号和密码是否正确
    var a = bcrypt.compareSync(password,model.password)
    if(model.username != username ||!a){
        return "账号密码不正确";
    }
    //登录成功生成token返回给客户端 
    const token = jwt.sign({username},'D31')
    return {
        token,
        meta:{
            msg:"登陆成功",
            status:200
        }
    };
}


async function test(){
    let user = {
        username:"D31",
        password:"ABC1231"
    }
    let a = await login(user);
    console.log(a);
    return;
}

test();